package com.example.taobaounion.view_component;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.example.taobaounion.R;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class TextFlowLayout extends ViewGroup {
    private List<String> mTextList = new ArrayList<>();


    private static final float DEFAULT_SPACE = 10;
    // Attribute3
    private float mItemHorizontalSpace;
    private float mItemVerticalSpace;

    // 本控件的宽度（加上子view)
    private int mSelfWidth;
    private int mItemMeasuredHeight;
    private onFlowTextItemClickListener mItemClickListener = null;

    public TextFlowLayout(Context context) {
        this(context, null);
    }

    public TextFlowLayout(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public TextFlowLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        // 去获取相关属性
        @SuppressLint("CustomViewStyleable") TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.FlowTextStyle);


        mItemHorizontalSpace = typedArray.getDimension(R.styleable.FlowTextStyle_horizontalSpace, DEFAULT_SPACE);
        mItemVerticalSpace = typedArray.getDimension(R.styleable.FlowTextStyle_horizontalSpace, DEFAULT_SPACE);

        typedArray.recycle();
    }

    // 单行
    private List<View> mLine = null;
    // 所有行
    private List<List<View>> mLines = new ArrayList<>();

    @SuppressLint("DrawAllocation")
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

        // 如果不存在子view 则直接返回
        if (getChildCount() == 0) {
            setMeasuredDimension(0, 0);
            return;
        }

        mLine = null;
        mLines.clear();

        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        // 测量
        // 测量孩子

        mSelfWidth = MeasureSpec.getSize(widthMeasureSpec) - getPaddingLeft() + getPaddingRight();

        for (int i = 0; i < getChildCount(); i++) {
            View lChildAt = getChildAt(i);

            if (lChildAt.getVisibility() != VISIBLE) {
                continue;
            }
            // 测量前
            measureChild(lChildAt, widthMeasureSpec, heightMeasureSpec);
            // 测量后

            if (mLine == null) {
                mLine = new ArrayList<>();
                mLine.add(lChildAt);
                mLines.add(mLine);
            } else {
                if (canbeAdd(lChildAt, mLine)) {
                    // 添加
                    mLine.add(lChildAt);
                } else {
                    // 新添加一行
                    mLine = new ArrayList<>();
                    mLine.add(lChildAt);
                    mLines.add(mLine);
                }
            }
        }

        mItemMeasuredHeight = getChildAt(0).getMeasuredHeight();

        // 测量自己
        // 本组合控件的高度加上子view
        int lSelfHeight = (int) (mLines.size() * getChildAt(0).getMeasuredHeight() + mItemVerticalSpace * (mLines.size() + 1));

        // 设置本控件的宽度和高度
        setMeasuredDimension(mSelfWidth, lSelfHeight);
    }

    /**
     * 判断当前行是否可以添加子view
     *
     * @param childAt 子view
     * @param line    当前行
     */
    private boolean canbeAdd(View childAt, List<View> line) {
        float lTotalWidth = childAt.getMeasuredWidth() + (line.size() + 1) * mItemHorizontalSpace;

        for (View view : line) {
            lTotalWidth += view.getMeasuredWidth();
        }

        return lTotalWidth <= mSelfWidth;
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        // 摆放孩子

        int lTopOffset = (int) mItemHorizontalSpace;
        for (List<View> lLine : mLines) {
            int lLeftOffset = 0;
            for (View lView : lLine) {
                lView.layout(lLeftOffset, lTopOffset, lLeftOffset + lView.getMeasuredWidth(), lTopOffset + lView.getMeasuredHeight());

                lLeftOffset += lView.getMeasuredWidth() + mItemHorizontalSpace;
            }

            lTopOffset += mItemMeasuredHeight + mItemHorizontalSpace;
        }
    }


    public void setTextList(List<String> textList) {

        removeAllViews();

        mTextList.clear();

        this.mTextList = textList;

        // make the last history at the first position
        Collections.reverse(mTextList);

        for (String lText : mTextList) {
            TextView item = (TextView) LayoutInflater.from(getContext()).inflate(R.layout.flow_text_view, this, false);

            item.setText(lText);

            item.setOnClickListener(v -> {
                if (mItemClickListener != null) {
                    mItemClickListener.onFlowItemClick(lText);
                }
            });
            // 添加子view
            addView(item);
        }
    }

    public int getContentSize() {
        return mTextList.size();
    }

    public void setonFlowTextItemClickListener(onFlowTextItemClickListener pClickListener) {
        this.mItemClickListener = pClickListener;
    }

    public interface onFlowTextItemClickListener {
        void onFlowItemClick(String text);
    }
}